package study.datastructure.array;/**
 * @program: datastructure
 * @author: lcy
 * @create: 2024-09-19 14:16
 */

import java.util.ArrayList;
import java.util.function.Consumer;

/**
 2024/9/19,
 */

//动态数组
public class DynamicArray {
    private  static int capacity=3;//容量
    private int size=0; //实际大小
    public  static int[] array={};

    public void addLast(int value) {
        add(size,value);
    }
    public void add(int index,int value) {
        checkAndGrow(index);

        //index [0,size)
        if(index>=0&&index<=size){
            //索引中的数index,size-1 均加一
            System.arraycopy(array,index,array,index+1,size-index);
            array[index] = value;
            size++;
        }else {
            System.out.println("index不符合条件");
        }
    }

    private void checkAndGrow(int index) {
        //懒加载
        if(size==0){
            array=new int[capacity];
        }

        //扩容
        if (index ==capacity){
            capacity+=capacity>>1; //1.5倍
            int[] newArray = new int[capacity];
            System.arraycopy(array,0,newArray,0,size);
            array=newArray;
        }
    }

    public void forEach(Consumer<Integer> consumer){ //函数式接口传递
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }
}
